package com.kb.job;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.kb.entity.ComponentData;
import com.kb.entity.ComponentDataHeaderField;
import com.kb.entity.Header;
import com.kb.mapper.es.ComponentDataHeaderFieldMapper;
import com.kb.mapper.es.ComponentDataHeaderMapper;
import com.kb.mapper.es.ComponentDataMapper;
import com.kb.service.gc.AggregationFieldService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 国创工软
 */

@Component
@Slf4j
public class InitAggregationFieldJob {

    //对应表的mapper
    @Resource
    private ComponentDataMapper componentDataMapper;

    @Resource
    private ComponentDataHeaderMapper componentDataHeaderMapper;

    @Resource
    private ComponentDataHeaderFieldMapper componentDataHeaderFieldMapper;

    @Resource
    private AggregationFieldService aggregationFieldService;


    @Scheduled(cron = "0 39 18 * * ?")
    public void initAggregationFieldJob() {
        log.info("聚合搜索初始化启动--");

        //分页查询，可自己显示
        List<ComponentData> dataList = componentDataMapper.selectList(null);
       int batchNum = dataList.size()/200;
        List<List<ComponentData>> partition = Lists.partition(dataList, 200);
        int i = 0;
        for (List<ComponentData> componentDataList : partition) {
            i++;
            Set<Long> setIds = componentDataList.stream().map(ComponentData::getSetId).collect(Collectors.toSet());

            List<Header> headerList = componentDataHeaderMapper.selectBatchIds(setIds);

            LambdaQueryWrapper<ComponentDataHeaderField> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(ComponentDataHeaderField::getSetId, setIds);

            List<ComponentDataHeaderField> headerFieldList = componentDataHeaderFieldMapper.selectList(queryWrapper);

            aggregationFieldService.handleAggregationField(dataList, headerList, headerFieldList);
            log.info("初始化搜索分类聚合字段总共{}批，第{}批完成", batchNum, i );
        }


    }
}
